<?php
namespace core\models;
/**
 * session存memcache
 * Class Sessions_Memcache
 * @author tie.Gump fixed by ZhouHaoHua <53027327@qq.com>
 */
class Sessions_Memcache {
    private $_life, $_name, $_C, $_key;

    function __construct($sessionName, $lifeLength = 1440) {
        $this->_key  = md5(Z_APP . '_Sessions_Memcache');
        $this->_life = $lifeLength;
        $this->_name = $sessionName;
        $this->_C    = \Z::Cache('Memcache', null); //new \Memcache;
        //$cw          = (new \config())->web();//Z_ENV
        //$this->_C->addserver(Z_MEMCACHE_HOST, Z_MEMCACHE_PORT);
        //$this->_C->connect($cw::Z_MEMCACHE_HOST, $cw::Z_MEMCACHE_PORT);

        session_set_save_handler(
            array($this, "open"),
            array($this, "close"),
            array($this, "read"),
            array($this, "write"),
            array($this, "destroy"),
            array($this, "gc")
        );
    }

    /**
     * 打开
     * @return bool
     */
    function open() {
        return true;
    }

    /**
     * 关闭
     * @return bool
     */
    function close() {
        return true;
    }

    /**
     * 读取
     * @param $id
     * @return int|mixed|string
     */
    function read($id) {
        $value = $this->_C->get(md5($this->_key . $id));
        if ($value)
            return $value;
        else
            return '';
    }

    /**
     * 写入
     * @param $id
     * @param $data
     * @return bool
     */
    function write($id, $data) {
        return $this->_C->set(md5($this->_key . $id), $data, 0, $this->_life);
    }

    /**
     * 删除
     * @param $id
     * @return bool
     */
    function destroy($id) {
        return $this->_C->delete(md5($this->_key . $id));
    }

    /**
     * 销毁过期的session 此操作交由memcache内部自动删除
     * @return bool
     */
    function gc() {
        return true;
    }

    function __destruct() {
        //$this->_C->close();
    }
}